<script setup>
  import {
    getCategoryList,
    getBookList,
    getBookCopyList,
    addBookCopy,
    deleteBookCopy,
    getbookShelfTree,
    addBook,
    borrowBook,
  } from '@/api'
  import { ElMessageBox } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { ref, onMounted, useTemplateRef } from 'vue'
  import { useDynamicForm } from '@/hooks'

  const { openForm } = useDynamicForm()
  const categoryList = ref([])
  const bookList = ref([])
  const searchText = ref('')
  const categoryId = ref('')
  const form = useTemplateRef('form')
  const bookShelfTree = ref([])

  const bookCopyTableColumns = [
    { label: 'Id', prop: 'id' },
    { label: '状态', prop: 'bookCopyStatus', filter: val => (val ? '借出' : '在馆') },
    { label: '操作', prop: 'option' },
  ]
  const bookTableColumns = [
    { label: 'Id', prop: 'id' },
    { label: '书名', prop: 'title' },
    { label: '作者', prop: 'author' },
    { label: '出版社', prop: 'publisher' },
    { label: '售价', prop: 'price' },
    { label: '分类', prop: 'categoryId', filter: val => categoryList.value.find(item => item.value === val)?.label },
    { label: '存放位置', prop: 'fullLocationPath', width: 300 },
  ]

  const handleGetCategoryList = () => {
    getCategoryList().then(res => {
      categoryList.value = res.data.map(item => ({ value: item.id, label: item.name }))
    })
  }

  const handleSearchBook = () => {
    const title = searchText.value || undefined
    const id = categoryId.value || undefined
    const p = getBookList({ title, categoryId: id }).then(res => {
      bookList.value = res.data.map(item => ({ ...item, bookCopies: [], got: false }))
    })

    form.value.load(p)
  }

  const handleGetBookCopies = (row, foucs = false) => {
    if (row.got && !foucs) return

    getBookCopyList(row.id).then(res => {
      const idx = bookList.value.findIndex(item => item.id === row.id)
      bookList.value[idx].got = true
      bookList.value[idx].bookCopies = res.data.map(({ id, bookCopyStatus }) => ({ id, bookCopyStatus }))
    })
  }

  const onChangeCategory = () => {
    handleSearchBook()
  }

  const onExpandChange = row => {
    handleGetBookCopies(row)
  }

  const onClickBorrowBook = (row, bookRow) => {
    const options = {
      title: '借阅书籍',
      fields: [{ label: '借阅时长', key: 'borrowDays', type: 'select', require: true }],
      onConfirm: (data, { close, setLoading }) => {
        const id = row.id

        setLoading(true)
        borrowBook({ bookCopyId: id, ...data })
          .then(() => {
            ElMessage.success('借阅成功')
            handleGetBookCopies(bookRow, true)
            close()
          })
          .finally(() => setLoading(false))
      },
    }

    options.fields[0].options = [1, 2, 3, 4, 5, 6, 7].map(item => ({ label: item + '天', value: item }))

    openForm(options)
  }

  const handleGetBookShelf = () => {
    getbookShelfTree().then(res => {
      const map = val => {
        val.forEach(item => {
          item.label = item.name
          item.value = item.id

          if (item.children) map(item.children)
        })
      }
      map(res.data)
      bookShelfTree.value = res.data
    })
  }

  onMounted(() => {
    handleGetCategoryList()
    handleSearchBook()
    handleGetBookShelf()
  })
</script>

<template>
  <page-layout>
    <template #header>
      <el-input
        v-model="searchText"
        placeholder="请输入书名或作者"
        style="width: 200px"
        clearable
        @blur="handleSearchBook"
      />
      <el-select
        v-model="categoryId"
        placeholder="选择图书分类"
        style="width: 200px"
        @change="onChangeCategory"
        clearable
      >
        <el-option v-for="item in categoryList" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <el-button icon="Search" @click="onChangeCategory">搜索</el-button>
    </template>

    <dynamic-table :data="bookList" :columns="bookTableColumns" ref="form" @expand-change="onExpandChange" row-key="id">
      <el-table-column type="expand" label="副本" width="100">
        <template #default="{ row }">
          <dynamic-table :columns="bookCopyTableColumns" :data="row.bookCopies">
            <template #option="{ row: r }">
              <el-button type="info" :disabled="r.bookCopyStatus !== 0" @click="onClickBorrowBook(r, row)">
                借阅
              </el-button>
            </template>
          </dynamic-table>
        </template>
      </el-table-column>
    </dynamic-table>
  </page-layout>
</template>

<style scoped lang="less"></style>
